<?php
class database extends MY_Controller{
	var $beforeFilter = array(
			'initAdmin' => array(
				'only' => array('admin','backup'),
			),
		);

	function __construct()
	{
		parent::MY_Controller();
		$this->datadir = FCPATH.'data/Backup/';
		$this->load->helper(array('url','system','form'));
	}

	

	function admin(){
		$dataList = $this->db->query("SHOW TABLE STATUS LIKE '".$this->db->dbprefix."%'")->result_array();
        foreach ($dataList as $row){
            $total += $row['Data_length'];
        }
        $this->assign['dataList'] = $dataList;
        $this->assign['total'] = $total;
        $this->display();
	}
	

	function backup(){
		$tables = $this->input->post('tables');
		if(!$tables){
			$this->showMessage('error_none_selected');
		}
		
		$dataList = $this->db->query("SHOW TABLE STATUS LIKE '".$this->db->dbprefix."%'")->result_array();
		foreach ($dataList as $row){
				$table_info[$row['Name']]=$row;
		}
		
		$sql='';
		$sql .= "-- Eusite SQL Backup\n-- Time:".date('Y-m-d H:i:s')."\n-- http://www.eshang.com \n\n";
		foreach($tables as $key=>$table) {
			$sql .= "--\n-- Eusite Table `$table`\n-- \n";
			$sql .= "DROP TABLE IF EXISTS `$table`;\n";
			$info = $this->db->query("SHOW CREATE TABLE  $table")->result_array();					
			$sql .= str_replace(array('USING BTREE','ROW_FORMAT=DYNAMIC'),'',$info[0]['Create Table']).";\n";
		}
		$tableid = 0;
		for(; $tableid < count($tables); $tableid++) {
			if($table_info[$tables[$tableid]]['Rows']>0){
				$sql .=  $this->_dumptablesql($tables[$tableid]);
			}
		}
		$filename = htmlspecialchars(strip_tags($_GET['filename']));
		$filename = !$filename ? 'Es_'.date('YmdHis') : $filename;
		$filename_valume = sprintf($filename."-%s".'.sql', 1);
 
		if(trim($sql)){
			$putfile=$this->datadir . $filename_valume;
			$r= file_put_contents($putfile , trim($sql));
		}
	 
		$this->showMessage('mes_success');
	}
	
	public function recover(){
		if($_GET['do']=='delete'){

			foreach ((array)$_POST['files'] as $r){
				unlink($r);
			}
			$this->showMessage('mes_success');
		}elseif($_GET['do']=='import'){
			header('Content-Type: text/html; charset=UTF-8');
			$filename = $_GET['filename'];
			$filelist = dir_list($this->datadir);
			foreach ((array)$filelist as $r){
				$file = explode('-',basename($r));
				if($file[0] ==$filename){
					$files[]  = $r;
				}
			}
			foreach((array)$files as $file){
				//读取数据文件
				$sqldata = file_get_contents($file);
				$sqlFormat = sql_split($sqldata, $this->db->dbprefix);
				foreach ((array)$sqlFormat as $sql){
						$sql = trim($sql);
						if (strstr($sql, 'CREATE TABLE')){
							preg_match('/CREATE TABLE `([^ ]*)`/', $sql, $matches);
							$ret =$this->excuteQuery($sql);
							//if($ret){echo   L('CREATE_TABLE_OK').$matches[0].' <br />';}else{echo 'Error sql:'.$sql;}exit;
						}else{
							$ret = $this->excuteQuery($sql);
						}
				}
				$this->showMessage('mes_success');
			}

		}else{
			$filelist = dir_list($this->datadir);
			foreach ((array)$filelist as $r){
				$filename = explode('-',basename($r));
				$files[] = array('path'=> $r,'file'=>basename($r),'name' => $filename[0], 'size' => filesize($r), 'time' => filemtime($r));
			}
			$this->assign['files']=$files;
			$this->display(null,'admin/database_recover');
		}
	}
	
	private function _dumptablesql($table){
		$insertsql = '';
		$selectsql = "SELECT * FROM $table";
		$tabledumped = 1;
		$row = $this->db->query($selectsql)->result_array();
		foreach($row as $key=>$val) {
			foreach ($val as $k=>$field){
				if(is_string($field)) {
					$val[$k] = '\''. mysql_real_escape_string($field).'\'';
				}elseif(empty($field)){
					$val[$k] = 'NULL';
				}
			}
			$insertsql .= "INSERT INTO `$table` VALUES (".implode(',', $val).");\n";
		}
		return $insertsql;
	}
	
	public function excuteQuery($sql='')
    {
        if(empty($sql)) {$this->showMessage('error_none_selected');}
        $queryType = 'INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|SELECT .* INTO|COPY|ALTER|GRANT|TRUNCATE|REVOKE|LOCK|UNLOCK';
        $data['result'] = $this->db->query($sql);
        $data['type'] = 'query';
        return $data;
    }
}